<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/29
 * Time: 15:35
 */
declare(strict_types=1);

namespace App\Service;
use App\Model\Dao\ChannelInfoDao;
use App\Model\Dao\RateCostDao;
use App\Model\Dao\RateCostRefDao;
use App\Model\Dao\StatMonthlyChannelDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderDisDao;
use App\Model\Dao\TradeOrderRefundDao;
use App\Utils\CustomUtils;
use Hyperf\Di\Annotation\Inject;

class StatChannelService
{

    /**
     * @Inject()
     * @var ChannelInfoDao
     */
    private $ChannelInfoDao;

    /**
     * @Inject()
     * @var RateCostDao
     */
    private $RateCostDao;

    /**
     * @Inject()
     * @var RateCostRefDao
     */
    private $RateCostRefDao;

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var TradeOrderDisDao
     */
    private $TradeOrderDisDao;

    /**
     * @Inject()
     * @var TradeOrderRefundDao
     */
    private $TradeOrderRefundDao;

    /**
     * @Inject()
     * @var StatMonthlyChannelDao
     */
    private $StatMonthlyChannelDao;

    /**
     * @param $startTime 开始时间
     * @param $endTime 结束时间
     * @param $statMonth 统计月份
     * @param array $channelNos 通道号，可以单独统计某个通道
     * @param bool $isForce 是否强制，是的话会把已经生成的软删除再生成
     */
    public function stat($startTime, $endTime, $statMonth, $channelNos = [], $isForce = false) {

        try {
            // 先取通道
            $channelList = null;
            if (empty($channelNos)) {
                $channelList = $this->ChannelInfoDao->getAll();
            } else {
                $channelList = $this->ChannelInfoDao->getByChannelNos($channelNos);
            }
            foreach ($channelList as $channel) {

                $this->statChannel($channel, $statMonth, $startTime, $endTime, $isForce);

            }
        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
        }

    }

    private function statChannel($channel, $statMonth, $startTime, $endTime, $isForce) {
        $isStat = $this->StatMonthlyChannelDao->getWhere([
            'channelId'     => $channel['id'],
            'statMonth'     => $statMonth,
            'delFlag'       => 0
        ]);

        if ($isForce && $isStat) {
            // 强制成功且有数据就删除
            $this->StatMonthlyChannelDao->del($isStat['id']);
        } else if (!$isForce && $isStat) {
            // 有数据就不管了
            return;
        }

        $rateCostRef = $this->RateCostRefDao->getWhere(['channelId' => $channel['id']]);
        if (empty($rateCostRef)) {
            CustomUtils::xzxDebug("通道：{$channel['channelName']} 未设置成本关联");
            return;
        }
        $rateCost = $this->RateCostDao->get($rateCostRef['rateCostId']);

        // 取数据
        $sum        = $this->TradeOrderDetailDao->getSumByTransStatusAndStartTimeAndEndTime(null, $channel['id'], [6], $startTime, $endTime);
        $sumFee     = $this->TradeOrderDetailDao->getSumByTransStatusAndStartTimeAndEndTime(null, $channel['id'], [], $startTime, $endTime);
        $sumRefund  = $this->TradeOrderRefundDao->getSumByHandleStatusAndStartTimeAndEndTime(null, $channel['id'], [3], $startTime, $endTime);
        $sumDis     = $this->TradeOrderDisDao->getSumByHandleStatusAndStartTimeAndEndTime(null, $channel['id'], [3], $startTime, $endTime);

        // 写统计表
        $data = [
            'id'                     => CustomUtils::createUUID(),
            'channelId'              => $channel['id'],
            'channelNo'              => $channel['channelNo'],
            'channelName'            => $channel['channelName'],
            'settleCurrency'         => $channel['settleCurrency'],

            'successCount'           => isset($sum['totalCount']) ? $sum['totalCount'] : 0,
            'totalCount'             => isset($sumFee['totalCount']) ? $sumFee['totalCount'] : 0,
            'disCount'               => isset($sumDis['transCount']) ? $sumDis['transCount'] : 0,
            'refundCount'            => isset($sumRefund['transCount']) ? $sumRefund['transCount'] : 0,

            'settleAmount'           => 0,
            'refundSettleAmount'     => 0,
            'disSettleAmount'        => 0,

            'statMonth'              => $statMonth,
            'statStartTime'          => $startTime,
            'statEndTime'            => $endTime,
            'delFlag'                => 0,
            'createTime'             => time()
        ];
        // 算一下几个百分比
        $data['serviceFeeRate'] = $rateCost['serviceFee'];
        $data['successRate'] = $data['totalCount'] == 0 ? 10000 : round($data['successCount'] / $data['totalCount'] * 10000);
        $data['refundRate'] = $data['totalCount'] == 0 ? 0 : round($data['refundCount'] / $data['totalCount'] * 10000);
        $data['disRate'] = $data['totalCount'] == 0 ? 0 : round($data['disCount'] / $data['totalCount'] * 10000);
        $this->StatMonthlyChannelDao->add($data);

    }

}